#!/bin/sh

machineid_enabled() {
    # On flasher we don't need persistent machine-id
    # shellcheck disable=SC2154
    if [ "$bootparam_flasher" = "true" ]; then
        echo "[INFO] Flasher detected. Avoiding persistent machine-id."
        return 1
    fi
    return 0
}

machineid_run() {
    # Mount the state partition - that's where we store the machine_id
    state_partition_path="$(get_state_path_from_label "resin-state")"
    if ! wait4file "$state_partition_path" "300"; then
        error "Timeout while waiting for resin-state partition to be detected."
        error "Not able to mount resin-state, machine-id will not be persistent."
	return
    fi

    info "Binding machine-id from ${state_partition_path}"
    if ! mount -t ext4 "$state_partition_path" "$ROOTFS_DIR"/mnt/state; then
        error "Not able to mount resin-state, machine-id will not be persistent."
        return
    fi

    # Mount machine-id
    if [ ! -e "$ROOTFS_DIR"/mnt/state/machine-id ]; then
        touch "$ROOTFS_DIR"/mnt/state/machine-id
    fi
    if ! mount -o bind "$ROOTFS_DIR"/mnt/state/machine-id "$ROOTFS_DIR"/etc/machine-id; then
	    error "Error while mounting persistent machine-id."
	    return
    fi
    info "Persistent machine-id mounted."
}
